from infoUi import wx,threading
from infoUi import myInfoUi
from mycom import mySerial

class myComUi(myInfoUi,mySerial):

    def __init__(self, parent=None, title="MyTest",pos = (1000,680),size = (1024,600)):
        wx.Frame.__init__(self,parent=parent, title=title,size=size)
        self.panel = wx.Panel(self,size = (1024,600))

    def setUpComUi(self):
        #初始化串口
        self.initMySer()

        #初始化串口UI界面
        self.comUiCtr={
            'com':'',
            'bps':'',
            'sendWind':'',
            'BoxSizer':'',
            'comOpenClose':'',
        }
        #串口配置组件
        sSer_box = wx.StaticBox(self.panel, -1, "Serail tool")
        self.comUiCtr['BoxSizer'] = wx.StaticBoxSizer(sSer_box,wx.HORIZONTAL)
        wOpt_box = wx.BoxSizer(wx.HORIZONTAL)
        dataSendWind_box = wx.BoxSizer(wx.VERTICAL)
        comSelect_box = wx.BoxSizer(wx.HORIZONTAL)
        comBps_box = wx.BoxSizer(wx.HORIZONTAL)
        comBnt_box = wx.BoxSizer(wx.HORIZONTAL)
        comConfig_box = wx.BoxSizer(wx.VERTICAL)

        #端口选择
        comList = self.listMyCom() #获取端口信息
        if comList == None:
            comList = ['None']
        com_label = wx.StaticText(self.panel,label = "端口号:",size=(60,-1))
        self.comUiCtr['com'] = wx.ComboBox(self.panel,value = comList[0],choices = comList,style=wx.CB_SORT,size=(150,25))

        comSelect_box.Add(com_label, proportion = 0)
        comSelect_box.Add(self.comUiCtr['com'], proportion = 1, flag=wx.ALL, border = 3)

        #波特率设置
        bpsList = ['115200','921600']
        bps_label = wx.StaticText(self.panel, label = "波特率:", size=(60,-1))
        self.comUiCtr['bps'] = wx.ComboBox(self.panel,value = '115200',choices = bpsList,style=wx.CB_SORT,size=(-1,25))

        comBps_box.Add(bps_label, proportion = 0)
        comBps_box.Add(self.comUiCtr['bps'], proportion = 1,flag=wx.ALL,border = 3)

        #发送窗口
        self.comUiCtr['sendWind'] = wx.TextCtrl(self.panel,style = wx.TE_MULTILINE|wx.HSCROLL,size=(-1,100))

        #操作按钮
        comSendData = wx.Button(self.panel,label = "发送数据")
        comOpenClose = wx.ToggleButton(self.panel,label = "打开串口")
        self.comUiCtr['comOpenClose'] = comOpenClose
        comCleanBnt = wx.Button(self.panel,label = "清除窗口")
        comBnt_box.Add(comOpenClose, proportion = 1,flag=wx.ALL,border = 3)
        comBnt_box.Add(comSendData, proportion = 1,flag=wx.ALL,border = 3)

        #串口组件布局
        comConfig_box.Add(comSelect_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        comConfig_box.Add(comBps_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        comConfig_box.Add(comBnt_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        comConfig_box.Add(comCleanBnt,proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)

        dataSendWind_box.Add(wOpt_box,proportion = 0)
        dataSendWind_box.Add(self.comUiCtr['sendWind'],proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)

        self.comUiCtr['BoxSizer'].Add(comConfig_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        self.comUiCtr['BoxSizer'].Add(dataSendWind_box,proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)

        #事件绑定
        self.comUiCtr['com'].Bind(wx.EVT_COMBOBOX_DROPDOWN,self.onflushCom)
        comOpenClose.Bind(wx.EVT_TOGGLEBUTTON, self.onOpenClose)
        comSendData.Bind(wx.EVT_BUTTON, self.onSendData)
        comCleanBnt.Bind(wx.EVT_BUTTON, self.onCleanInfoUi)

    def comDateRcv(self):
        buf={'data': ''}
        while(self.ser.isOpen()):
            try:
                self.recvDataLine(buf)
                self.debugToUi(buf['data'])
            except  Exception as err:
                print(err)
                self.closeSerial()
        if(self.ser.isOpen()):
            pass
        else:
            self.changeComStatus()
            print("COM disconnect !\r\n")

    def onflushCom(self,evt):
        comList = self.listMyCom() #获取端口信息
        if comList == None:
            comList = ['None']
        obj = evt.GetEventObject()
        oldView = obj.GetValue()
        print('old:'+obj.GetValue())
        obj.SetItems(comList)
        obj.SetValue(oldView)

    def onOpenClose(self,evt):
        obj = evt.GetEventObject()
        checked = obj.GetValue()
        if (checked):
            #获取串口名
            if(self.comUiCtr['com'].GetValue() != '' and self.comUiCtr['com'].GetValue() != 'None'):
                prot = str(self.comUiCtr['com'].GetValue()).split(' ')[0]
            else:
                self.warningDebug("no com find!\r\n")
                obj.SetValue(0)
            #获取波特率
            if(self.comUiCtr['bps'].GetValue() != ''):
                bps = int(self.comUiCtr['bps'].GetValue())
            else:
                bps = 115200
            if(self.getSerialOrNone(prot) == None):
                self.warningDebug(" COM cann't be use!\r\n")
                obj.SetValue(0)
            else:
                self.openSerial(prot,bps)
                obj.SetLabel('关闭串口')
                #启动数据接收线程
                self.otaThread = threading.Thread(target=self.comDateRcv, name='fota', daemon=True)
                self.otaThread.start()
        else:
            self.closeSerial()
            obj.SetLabel('打开串口')
        self.changeComStatus()

    def changeComStatus(self):
        if(self.uiStatusBar['Text1'] != ''):
            if(self.ser.is_open):
                open = '已打开'
            else:
                open = '已关闭'
            comInfo = ("%s %s %dbps,%d,%d,%c"    %(self.ser.port,\
                open, \
                self.ser.baudrate,\
                self.ser.bytesize,\
                self.ser.stopbits,\
                self.ser.parity))
            #print(comInfo)
            self.statusTextSet(1,comInfo)

    def onCleanInfoUi(self,evt):
        self.infoUiCtr['InfoText'].Clear()
        pass

    def onSendData(self,evt):
        data = self.comUiCtr['sendWind'].GetValue()
        data = data.replace("\r","")
        data = data.replace("\n","")
        self.sendATCmd(data+"\r\n")


#comUi demo
if __name__ == '__main__':
    app = wx.App()
    frame = myComUi(title="While there is life,there is hope.")
    frame.setUpInfoUi()
    frame.setUpComUi()
    mainBox = wx.BoxSizer()
    mainBox.Add(frame.infoUiCtr['BoxSizer'],proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)
    mainBox.Add(frame.comUiCtr['BoxSizer'],proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
    frame.panel.SetSizer(mainBox)
    frame.Show()
    app.MainLoop()


